package com.ruoyi.charge.utils;

import com.ruoyi.common.utils.RedisUtil;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;

/**
 * 序列号生成工具
 *
 * @author laifeng
 * @version 1.0
 * @date 2025/7/16
 */
@Component
public class SerialUtils {
    @Inject
    private static RedisUtil redisUtil;
    private static final String KEY = "ykc_serial";
    private static final int MAX_SEQUENCE = 65535; // unsigned short 最大值
    private static final String FEE_MODEL_KEY = "ykc_fee_model";


    public static short createSerialNumber(String chargerSn) {

        // 使用increment方法获取当前值并+1
        Long current = redisUtil.hIncrBy(KEY, chargerSn, 1);

        if (current == null || current > MAX_SEQUENCE) {
            // 如果为空或溢出，则重置为 0
            resetSequence(chargerSn);
            return 0;
        }

        return (short) (current & 0xFFFF); // 转换为无符号short范围（0~65535）
    }

    public static short createFeeModelSerialNumber(String chargerSn) {
        Long current = redisUtil.hIncrBy(FEE_MODEL_KEY, chargerSn, 1);
        if (current == null || current > MAX_SEQUENCE) {
            resetSequence(chargerSn);
            return 0;
        }
        return (short) (current & 0xFFFF);

    }


    // 网络断开重连时调用，重置序列号为0
    public static void resetSequence(String chargerSn) {
        redisUtil.hSet(KEY, chargerSn, 0);
    }


}
